package gui.author;


import gui.CAControl;
import gui.CAFrame;

import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Observable;
import java.util.Observer;
import java.util.Scanner;

import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;

import caobject.Conference;
import caobject.EnumRole;
import caobject.Manuscript;
import caobject.User;

/**
 * Conference Assistant South Panel.
 *
 * @author Bob Rankin
 * @author Brian M. Luger
 * @version 11/27/2011
 */
@SuppressWarnings("serial")
public class AuthorSouthPanel extends JPanel implements Observer {
	
 /**
  * Parent Frame
  */
 private final CAFrame my_parent;

 /* 
  * 	 * Panel Manuscript List Combo Box
  */
 private final JComboBox my_manuscript_list 
 		= new JComboBox();	

 /*
  * Panel Text Field
  */
 private final JTextField my_manuscriptField 
 		= new JTextField(10);	

 /*
  * Panel Buttons
  */
 private final JButton my_submitButton
		= new JButton("Submit Paper");	
 private final JButton my_mainMenuButton
	 	= new JButton("Main Menu");
	
 /*
  * Panel Button Group & Radio Buttons
  */
 private final ButtonGroup my_buttonGroup
		= new ButtonGroup();
 private final JRadioButton my_newPaperRadio
		= new JRadioButton("New");
 private final JRadioButton my_replacePaperRadio = 
		new JRadioButton("Replace");
	
 /*
  * Panel File Chooser
  */
 private final JFileChooser my_fileChooser 
 		= new JFileChooser();
	
 /*
  * Panel Conference Reference
  */
 private final Conference my_conf;
	
 /*
  * Panel Control Reference
  */
 private final CAControl my_control;
	
 /**
  * Conference Assistant South Panel Constructor
  * 
  * @param the_conf Conference Reference
  * @param the_control Control Reference
  */
 public AuthorSouthPanel(final CAFrame parentFrame, 
		final Conference the_conf, 
		final CAControl the_control) 
 {
  my_parent = parentFrame;
  my_conf = the_conf;
		
  my_control = the_control;
  my_control.addObserver(AuthorSouthPanel.this);
		
  setup();
 }
	
 /**
  * Panel Setup Method
  */
 private void setup() 
 {
  setLayout(new FlowLayout(FlowLayout.CENTER));
		
  // Submit Button
  my_submitButton.addActionListener(new ActionListener() 
   {
	public void actionPerformed(final ActionEvent event) 
	 {
	  if((my_control.getManuscriptTitle().length() > 0
		&& my_control.getSelectedUser().length() > 0) 
		&& ((!my_control.getSelectedMan().equalsIgnoreCase("None Selected")
		&& my_replacePaperRadio.isSelected())
		|| my_newPaperRadio.isSelected())) 
	  {
	   			
		// Manuscript Text...
		String manuscriptText = "";
					
		// Create a new User
		final User aUser = new User(
			my_control.getSelectedUser(), EnumRole.AUTHOR);
					
		int open = my_fileChooser.
		showOpenDialog(AuthorSouthPanel.this);
					
		if (open == JFileChooser.APPROVE_OPTION) 
		{
		 String ft = new String(my_fileChooser.
				 getSelectedFile().toString());
		 if (ft.length() > 4)
		 {
		  int ftl = ft.length() - 4;
		  String fte = new String(ft.substring(ftl));
		  if (fte.equalsIgnoreCase(".txt"))
		  {
		   Calendar xday = new GregorianCalendar(1998, 
				   Calendar.DECEMBER, 25);
		   xday = my_conf.getDeadline(0);
		   Date yday = xday.getTime();
		   Calendar zday = Calendar.getInstance();
		   java.util.Date currentDate = zday.getTime();		   
		   if (currentDate.before(yday))
		   {
			 manuscriptText = importText(
				my_fileChooser.getSelectedFile());
			 						
			final Manuscript aManuscript = 
			    new Manuscript(aUser.getUserName(), 
			my_control.getManuscriptTitle(), 
				manuscriptText);
												
			if (my_replacePaperRadio.isSelected())
			{
			 final Manuscript bManuscript = 
			 my_conf.getAManuscript(aUser.getUserName(), 
			 my_control.getSelectedMan());   
			 												
			 my_conf.replaceManuscript(bManuscript, 
			   aManuscript);

			 // Manuscript Confirmation Dialog
			 JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
			 "Manuscript was successfully replaced!", 
			 "Manuscript Replaced", 
			 JOptionPane.INFORMATION_MESSAGE);
			}
			else
			{
			 my_conf.addManuscript(aManuscript);

			// Manuscript Confirmation Dialog
			JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
			"Manuscript was successfully submitted!", 
			"Manuscript Submitted", 
			JOptionPane.INFORMATION_MESSAGE);
		   }
		   my_manuscript_list.removeAllItems();
		   my_manuscript_list.addItem("None Selected");
		   for (Manuscript bManuscript : my_conf.getManuscripts()) 
		   {
		    if (bManuscript.getAuthor().
				equalsIgnoreCase(my_control.getSelectedUser())) 
			{
			 my_manuscript_list.addItem(bManuscript.getTitle());
			}
		   }
		   my_control.setSelectedMan(my_manuscript_list);
//		   my_manuscript_list.setEditable(false);
		   }
		   else
		   {
			   // Manuscript Confirmation Dialog
			   JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
			   "Submission Deadline Passed!", 
			   "Manuscript NOT Submitted", 
			   JOptionPane.INFORMATION_MESSAGE);
		   }
		  }
		  else
		  {
			   // Manuscript Confirmation Dialog
			   JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
			   "Non text file choosen!", 
			   "Manuscript NOT Submitted", 
			   JOptionPane.INFORMATION_MESSAGE);
		  }
		 }
		 else
		 {
			   // Manuscript Confirmation Dialog
			   JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
			   "File name too short!", 
			   "Manuscript NOT Submitted", 
			   JOptionPane.INFORMATION_MESSAGE);
		 }
	    }
	   }
	   else if (my_control.getManuscriptTitle().length() <= 0)
	   {
		// Manuscript Confirmation Dialog
		JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
				"Manuscript title missing!", 
				"Manuscript NOT Submitted", 
				JOptionPane.INFORMATION_MESSAGE);
	   }
	   else if (my_control.getSelectedUser().length() <= 0)
	   {
		// Manuscript Confirmation Dialog
		JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
				"User ID missing!", 
				"Manuscript NOT Submitted", 
				JOptionPane.INFORMATION_MESSAGE);
	   }
	   else if (my_control.getSelectedMan().equalsIgnoreCase("None Selected")
			   	&& my_replacePaperRadio.isSelected())
	   {
		// Manuscript Confirmation Dialog
		JOptionPane.showMessageDialog(AuthorSouthPanel.this, 
				"No manuscript selected to replace!", 
				"Manuscript NOT Replaced", 
				JOptionPane.INFORMATION_MESSAGE);
	  }
	  my_control.setManuscriptTitle("");
	 			
	 }
	});
		
  		add(my_submitButton);
		
		// Main Menu Button
		my_mainMenuButton.addActionListener(new ActionListener() 
		{
			public void actionPerformed(final ActionEvent event) 
			{
				my_parent.displayWelcome();
			}
		});
		
		add(my_mainMenuButton);
		
		// Paper Radio Buttons
		my_buttonGroup.add(my_newPaperRadio);
		my_buttonGroup.add(my_replacePaperRadio);
		my_newPaperRadio.setSelected(true);
		
		add(my_newPaperRadio);
		add(my_replacePaperRadio);
		
		// Title Text Field
		add(new JLabel("Man. Title: "));
		my_manuscriptField.addFocusListener(new FocusListener() 
		{

			@Override
			public void focusGained(FocusEvent arg0) {
				// Do Nothing...
			}

			@Override
			public void focusLost(FocusEvent arg0) {
				my_control.setManuscriptTitle(
						my_manuscriptField.getText());
				
			}
			
		});
		add(my_manuscriptField);
		
		// Manuscript JComboBox
		add(new JLabel("Man. List: "));
		my_manuscriptField.addFocusListener(new FocusListener() 
		{

			@Override
			public void focusGained(FocusEvent arg0) {
				// Do Nothing...
			}

			@Override
			public void focusLost(FocusEvent arg0) {
				my_control.setManuscriptTitle(
						my_manuscriptField.getText());
				
			}
			
		});
		my_manuscript_list.setEditable(true);
		my_manuscript_list.removeAllItems();
		my_manuscript_list.addItem("None Selected");
		for (Manuscript aManuscript : my_conf.getManuscripts()) 
		{
			if (aManuscript.getAuthor().
				equalsIgnoreCase(my_control.getSelectedUser())) 
			{
				my_manuscript_list.addItem(aManuscript.getTitle());
			}
		}
		my_control.setSelectedMan(my_manuscript_list);
		my_manuscript_list.setEditable(false);
		add(my_manuscript_list);
		
	}
	
	/**
	 * Private Helper Method for parsing .txt files.
	 * 
	 * @param the_textFile File to be parsed.
	 * 
	 * @return String containing the text from the file.
	 */
	private String importText(final File the_textFile) 
	{
		final Scanner aScanner;
		final StringBuilder sb = new StringBuilder();
		
		try {
			aScanner = new Scanner(the_textFile);
			
			while (aScanner.hasNextLine()) {
				sb.append(aScanner.nextLine() + "\n");
			}
		} catch (IOException e) {
			// TODO: Implement Sufficient catch.
			System.err.println("[ERROR] - Problem parsing file!");
		}
		
		return sb.toString();
	}

	/**
	 * Method used to update the panel
	 */
	@Override
	public void update(final Observable the_observable, 
			final Object the_obj) {
		my_manuscriptField.setText(
				my_control.getManuscriptTitle());
		
	}
}
